import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:flutter_yres/model/shop/tbcate_model.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:dio/dio.dart';
import 'package:flutter_yres/model/shop/tbk_list_model.dart';
import 'package:flutter_yres/pages/shop/shop_detail_page.dart';
import 'package:flutter_yres/model/shop/hdk_list_model.dart';

class TBListPage extends StatefulWidget {
  String search;

  TBListPage({Key key, this.search}) : super(key: key);

  @override
  _TBListPageState createState() => _TBListPageState(search);
}

class _TBListPageState extends State<TBListPage> {
  String search;
  _TBListPageState(this.search);

  List<CateModelData> subs = []; //淘宝子级分类数组
  List<TBKListModelData> shopData = []; //商品列表
  // var search = '';
  int page_no = 1;
  EasyRefreshController _controller = new EasyRefreshController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(''),
        ),
        body: Container(
          color: Colors.white,
          child: _buildSub(),
        ));
  }

  //其他类别主页内容
  Widget _buildSub() {
    return Container(
      child: new EasyRefresh(
        //刷新  加载组件
        controller: _controller,
        child: CustomScrollView(slivers: <Widget>[
          // SliverGrid(
          //   gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
          //     maxCrossAxisExtent: (kScreenWidth - kMargin20) / 4,
          //     mainAxisSpacing: 10.0,
          //     crossAxisSpacing: 10.0,
          //     childAspectRatio: 1.15, //子控件宽高比
          //   ),
          //   delegate: SliverChildBuilderDelegate(
          //     (BuildContext context, int index) {
          //       return _itemBuilder(context, subs[index]);
          //     },
          //     childCount: subs.length,
          //   ),
          // ),
          SliverToBoxAdapter(
            child: Container(
                height: ScreenUtil.getInstance().setHeight(60),
                child: Column(
                  children: <Widget>[_buildPopHeader()],
                )),
          ),
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) -ScreenUtil.getInstance().setWidth(10)) / 2,
              mainAxisSpacing: 10.0,
              crossAxisSpacing: 15.0,
              childAspectRatio: 0.6, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return shopData.length > 0
                    ? getItemContainer(context, index)
                    : Container();
              },
              childCount: shopData.length,
            ),
          ),
        ]),
        onRefresh: () async {
          page_no = 1;
          getTBKShopList(this.search);
        },
        onLoad: () async {
          page_no++;
          getTBKShopList(this.search);
        },
      ),
    );
  }

  //条件筛选头部
  _buildPopHeader() {
    return Container(
      height: ScreenUtil.getInstance().setHeight(60),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "综合",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "销量",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "价格",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "佣金",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
        ],
      ),
    );
  }

//商品单个cell
  getItemContainer(BuildContext context, int index) {
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24))),
        TextSpan(
            text: shopData[index].zk_final_price,
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(32))),
        TextSpan(
          text: shopData[index].reserve_price,
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(24),
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var quanHeader = Container(
      width: ScreenUtil.getInstance().setWidth(40),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_header.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
    var quan = Container(
      width: ScreenUtil.getInstance().setWidth(70),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_footer.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
          child: Text(
        shopData[index].coupon_amount == null
            ? '0元'
            : shopData[index].coupon_amount + '元',
        style: TextStyle(color: Colors.white, fontSize: ScreenUtil.getInstance().setSp(24)),
      )),
    );
    var yongjin = Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), 0, ScreenUtil.getInstance().setWidth(20), 0),
      height: ScreenUtil.getInstance().setWidth(34),
      color: Color.fromRGBO(250, 226, 226, 1),
      child: Center(
          child: Text('预估赚¥' + shopData[index].commission,
              style: TextStyle(color: Colors.red,fontSize: ScreenUtil.getInstance().setSp(20)))),
    );
    return GestureDetector(
      onTap: (){
        HDKListModelData model = new HDKListModelData();
          model.itemid = shopData[index].num_iid;
        Navigator.push(
            context,
            MaterialPageRoute(
                //导航打开新视图
                builder: (context) =>
                    ShopDetailPage(hdkmodel: model) //打开第二个页面，并传值，传递值的名称是model
                ));
      },
      child:Container(
        color: Colors.white,
        margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(10), 0, ScreenUtil.getInstance().setWidth(10), 0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Image.network(
              shopData[index].pict_url.replaceAll("\\", "/"),
              width: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
              height: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
            ),
            Text(shopData[index].title, maxLines: 2,style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24)),),
            Container(
              margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
              child: price,
            ),
            Container(
              margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
              child: Text('已售' + shopData[index].volume,
                  style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24), color: Colors.grey)),
            ),
            Container(
              margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
              child: Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Row(
                      children: <Widget>[quanHeader,Expanded(child:quan) ],
                    ),
                  ),
                  Expanded(flex: 2, child: yongjin)
                ],
              ),
            )
          ],
        ))
    ) ;
  }

  @override
  void initState() {
    getTBKShopList(this.search);
    super.initState();
  }

/*淘宝子级列表*/
  // getTBSubCatList(String pid) async {
  //   FormData data = new FormData.fromMap({'pid': pid});
  //   Response<String> response =
  //       await HttpUtil().post(Api.GetTBSubListByParentUrl, data: data);
  //   Map userMap = json.decode(response.data);
  //   CateModelEntity itemEntity = new CateModelEntity.fromJson(userMap);
  //   if (itemEntity.code == 1) {
  //     if (mounted) {
  //       setState(() {
  //         subs.clear();
  //         subs = itemEntity.data;
  //         if (subs.length > 0) {
  //           search = subs[0].name;
  //           getTBKShopList();
  //         }
  //       });
  //     }
  //   }
  // }

  /*获取淘宝客商品列表（新）*/
  //GetTbkList_newUrl
  getTBKShopList(String search) async {
    FormData data = new FormData.fromMap(
        {'search': search, 'page_size': 10, 'page_no': page_no});
    Response<String> response =
        await HttpUtil().post(Api.GetTbkList_newUrl, data: data);
    Map userMap = json.decode(response.data);
    TBKListModelEntity itemEntity = new TBKListModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          if (page_no == 1) {
            shopData.clear();
            shopData = itemEntity.data;
          } else {
            shopData.addAll(itemEntity.data);
          }
        });
      }
    }
  }
}
